'''
Created on 31 mai 2011

@author: remidou
'''
import sys

def ingredient_ratings(product):
    ratings = []
    try:
        #for pi in ProductIngredient.objects.filter(product=self):
        for product_ingredient in product.productingredient_set.all():
            ratings.append(product_ingredient.ingredient.rating)
        result = int(sum(ratings))
    except:
        result = sys.exc_info()
    if (result>100):
        return 100
    return result

def packaging_ratings(product):
    ratings = []
    try:
        #for pi in ProductIngredient.objects.filter(product=self):
        for product_packaging in product.productpackaging_set.all():
            ratings.append(product_packaging.packaging.rating)
        result = int(sum(ratings))
    except:
        result = sys.exc_info()
    if (result>100):
        return 100
    return result

def weight_ratings(product):
    packagingPercent = weight_percent(product)
    if (packagingPercent is None):
        return None
    result = int(packagingPercent)
    if (result>100):
        return 100
    return result

def ratings(product):
    result = int((weight_ratings(product) + packaging_ratings(product) + ingredient_ratings(product))/3)
    if (result>100):
        return 100
    return result

def weight_percent(product):
    if ((product.nude_weight is None) or (product.full_weight is None)):
        return None
    packagingPercent = (1 - (product.nude_weight / product.full_weight)) * 100
    return int(packagingPercent)

def ingredient_ratings_detail(product):
    ratings = ''
    try:
        #for pi in ProductIngredient.objects.filter(product=self):
        for product_ingredient in product.productingredient_set.all():
            ratings = ratings + '+' + product_ingredient.ingredient.name + '/'+str(product_ingredient.ingredient.rating)
        result = ratings
    except:
        result = sys.exc_info()
    return result
